package com.study.oauth2demo.controller;

import com.study.oauth2demo.entity.UserDto;
import com.study.oauth2demo.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@RestController
public class IndexController {

	@Autowired
	private AuthenticationService authenticationService;

	@GetMapping(value = "/hello", produces = "text/plain;charset=utf-8")
	public String hello() {
		return "hello spring boot";
	}

	@PostMapping(value = "/login", produces = "text/plain;charset=utf-8")
	public ModelAndView login(ModelAndView mv, HttpSession session,
							  String name, String password) {

		try {
			UserDto dto = authenticationService.authentication(name, password);
			mv.addObject("user", dto.toString());
			session.setAttribute(UserDto.SESSION_KEY, dto);
		}catch (Exception e){
			mv.addObject("user", e.getMessage());
		}
		mv.setViewName("/index2");
		mv.addObject("name", name);
		mv.addObject("password", password);
		return mv;
	}

	@GetMapping(value = "/anymouse", produces = "text/plain;charset=utf-8")
	public String anymouse(HttpSession session){
		String fullName;
		Object object = session.getAttribute(UserDto.SESSION_KEY);
		if (object == null){
			fullName = "anymouse";
		}else {
			fullName = ((UserDto)object).getName();
		}

		return fullName;
	}

	@GetMapping(value = "/r1", produces = "text/plain;charset=utf-8")
	public String r1(){
		return "resource: r1";
	}

	@GetMapping(value = "/r2", produces = "text/plain;charset=utf-8")
	public String r2(){
		return "resource: r2";
	}

	@GetMapping(value = "/logout", produces = "text/plain;charset=utf-8")
	public String logout(HttpSession session){
		session.invalidate();
		return "logout success";
	}

	@RequestMapping(value = "/index", produces = "text/plain;charset=utf-8")
	public ModelAndView test(ModelAndView mv) {
		mv.setViewName("/index");
		mv.addObject("title","欢迎使用Thymeleaf!");
		return mv;
	}
}
 
